package com.ellfors.common.utils

import android.app.Activity
import android.content.Context
import android.content.res.Resources
import android.util.DisplayMetrics
import android.util.TypedValue

/**
 * DensityUtil
 * 2021-04-30 19:32
 */
object DensityUtil {

    fun getScreenWidth(context: Activity): Int {
        val outMetrics = DisplayMetrics()
        context.windowManager.defaultDisplay.getMetrics(outMetrics)
        return outMetrics.widthPixels
    }

    fun getScreenHeight(context: Activity): Int {
        val outMetrics = DisplayMetrics()
        context.windowManager.defaultDisplay.getMetrics(outMetrics)
        return outMetrics.heightPixels
    }

    fun dip2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f * (if (dpValue >= 0.0f) 1 else -1).toFloat()).toInt()
    }

    fun dimenDip2px(context: Context, dimenId: Int): Int {
        val value = context.resources.getDimension(dimenId)
        return dip2px(context, value / context.resources.displayMetrics.density)
    }

    fun px2dip(context: Context, pxValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (pxValue / scale + 0.5f * (if (pxValue >= 0.0f) 1 else -1).toFloat()).toInt()
    }

    fun px2sp(context: Context, pxValue: Float): Int {
        val scale = context.resources.displayMetrics.scaledDensity
        return (pxValue / scale + 0.5f * (if (pxValue >= 0.0f) 1 else -1).toFloat()).toInt()
    }

    fun sp2px(context: Context, spValue: Float): Int {
        val scale = context.resources.displayMetrics.scaledDensity
        return (spValue * scale + 0.5f * (if (spValue >= 0.0f) 1 else -1).toFloat()).toInt()
    }

    fun dp2px(dp: Float): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, dp, Resources.getSystem().displayMetrics
        ).toInt()
    }

    fun dp2px(dp: Int): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), Resources.getSystem().displayMetrics
        ).toInt()
    }

    fun sp2px(sp: Int): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), Resources.getSystem().displayMetrics
        ).toInt()
    }
}